//
//  HTUserAccountViewModel.swift
//  mySinaBlog
//
//  Created by whtapple on 3/24/16.
// https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.006ndg5GEwpRuCea29479d2a0AQ1Hn
//

import UIKit

class HTUserAccountViewModel: NSObject {
//单例
    static let sharedInstance: HTUserAccountViewModel = HTUserAccountViewModel()
    private override init() {
        super.init()
        userAccount = loadUserAccount()
//        print("userAccount:\(userAccount)")
    }
    //账号路径
    private let acountpath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    //账号
    var userAccount: HTuserCount?
//    是否登陆过
    func isLogin() ->Bool {
//        print("isLogin. userAccount = \(userAccount)")
//        print("\(acountpath)")
            return userAccount != nil
        
    }
//    var isLogin: Bool{
//        get{
////             print("isLogin. userAccount = \(userAccount)")
//            return userAccount != nil
//        }
//    }
    ///加载access_token
    func loadAccessToken(code: String, completion: (error: NSError?)->()){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        //发送 POST 请求
       HTNetworkTool.sharedInstanse.AFNManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//        print("result:\(result)")
        if let dict = result as? [String: AnyObject]{
            self.userAccount = HTuserCount(dict: dict)
            self.saveUserAccount()
            completion(error: nil)
        }
        }) { (_, error) -> Void in
            print("连接失败")
            completion(error:error)
        }

    }
    ///加载用户信息
    func loadUserInfo(completion: (error: NSError?) -> ()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["access_token" : userAccount!.access_token!,
            "uid" : userAccount!.uid!
        ]
        HTNetworkTool.sharedInstanse.AFNManager.GET(urlString, parameters: params, progress: nil, success:
            { (_, result) -> Void in
//             print("result = \(result)")
                if let dict = result as? [String:AnyObject]{
                    self.userAccount?.screen_name = dict["screen_name"] as? String
                    self.userAccount?.avatar_large = dict["avatar_large"] as? String
//                     print("result = \(self.userAccount!.screen_name)\(self.userAccount!.avatar_large)")
                    self.saveUserAccount()
                    
                }
            }) { (_, error) -> Void in
                print("error = \(error)")
        }
    }
    //保存模型到沙盒
    private func saveUserAccount(){
        //有账号才保存
        if userAccount != nil {
//            print("\(userAccount),\(acountpath)")
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: acountpath)
        }
    }
    //从沙盒中加载数据
    private func loadUserAccount() -> HTuserCount? {
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(acountpath) as? HTuserCount
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            return userAccount
        }
        return nil
    }

}
